package com.ruoyi.common.utils;

import cn.hutool.core.date.DateUtil;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.joda.time.DateTime;
import org.joda.time.Interval;

import java.lang.management.ManagementFactory;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

/**
 * 时间工具类
 *
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {

    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYYMM = "yyyyMM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    public static String DD = "dd";

    private static String[] parsePatterns = {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM", "yyyyMM", "yyyy"};

    /**
     * 获取开始时间
     *
     * @param date
     *
     * @return
     */

    public static String getBeginDate (Date date) {
        if (date == null) {
            return null;
        }

        String beginDate = DateUtil.format(date, "yyyy-MM-dd 00:00:00");

        return beginDate;
    }

    /**
     * 获取结束时间
     *
     * @param date
     *
     * @return
     */
    public static String getEndDate (Date date) {
        if (date == null) {
            return null;
        }

        String beginDate = DateUtil.format(date, "yyyy-MM-dd 23:59:59");
        return beginDate;
    }

    /**
     * 时间相减，返回时间戳，单位毫秒。
     *
     * @param endDate
     *         开始时间
     * @param beginDate
     *         结束时间
     *
     * @return
     */
    public static long subtract (Date endDate, Date beginDate) {
        if (endDate == null || beginDate == null) {
            return -1L;
        }
        long endTimestamp = endDate.getTime();
        long beginTimestamp = beginDate.getTime();

        return endTimestamp - beginTimestamp;
    }

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate () {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate () {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime () {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow () {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow (final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime (final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr (final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime (final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath () {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime () {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate (Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate (String date,String format) {
        if (date == null || format==null) {
            return null;
        }
        try {
            SimpleDateFormat formats=new SimpleDateFormat(format);
            return formats.parse(date);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate () {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 当天剩余时长（毫秒）
     */
    public static long getThatveryDateMilliSecond () {
        long milliSecondsLeftToday = 86400000 - DateUtils.getFragmentInMilliseconds(Calendar.getInstance(),
                Calendar.DATE
        );
        return milliSecondsLeftToday;
    }


    /**
     * 当天剩余时长（秒）
     */
    public static long getThatveryDateSecond () {
        long secondsLeftToday = 86400 - DateUtils.getFragmentInSeconds(Calendar.getInstance(), Calendar.DATE);
        return secondsLeftToday;
    }


    /**
     * 计算两个时间差
     */
    public static String getDatePoor (Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 计算两个时间差(天)
     */
    public static long getDayPoorDay (Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        // 获得两个时间的毫秒时间差异
        endDate = DateUtils.parseDate(DateUtils.parseDateToStr(YYYY_MM_DD, endDate));
        nowDate = DateUtils.parseDate(DateUtils.parseDateToStr(YYYY_MM_DD, nowDate));
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        return day;
    }

    /**
     * 当月剩余天数
     *
     * @param date
     *         格式yyyy-MM-dd
     */
    public static Integer monthEndNum (String date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date dateTime = null;
        try {
            dateTime = format.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar c = Calendar.getInstance();
        c.setTime(dateTime);
        int today = c.get(Calendar.DAY_OF_MONTH);
        int last = c.getActualMaximum(Calendar.DAY_OF_MONTH);
        return last - today;
    }
    
    /**
     * 计算两个时间差（小时）
     */
    public static Double getDayPoorHour (Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少小时
        long hour = diff / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        double l = new BigDecimal(min).divide(new BigDecimal(60), 2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return hour + l;
    }


    /**
     * 计算两个时间差（分钟）
     */
    public static long getDayPoorminute (Date endDate, Date nowDate) {
    /*    long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;*/
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少分钟
        long min = diff / nm;
        return min;
    }


    /**
     * 计算两个时间差（秒）
     */
    public static long getDayPoorSecond (Date endDate, Date nowDate) {
        long nm = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少秒
        long min = diff / nm;
        return min;
    }

    /**
     * 获取某天的时间,支持自定义时间格式
     *
     * @param simpleDateFormat
     *         时间格式,yyyy-MM-dd HH:mm:ss
     * @param index
     *         为正表示当前时间加天数，为负表示当前时间减天数
     *
     * @return String
     */
    public static String getTimeDay (String simpleDateFormat, int index) {
        //设置时区
        TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
        TimeZone.setDefault(tz);
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat fmt = new SimpleDateFormat(simpleDateFormat);
        calendar.add(Calendar.DAY_OF_MONTH, index);
        String date = fmt.format(calendar.getTime());
        return date;
    }

    /**
     * 加多少秒
     *
     * @param date
     *         时间
     * @param addTime
     *         秒数据
     *
     * @return
     */
    public static Date addSecondTime (Date date, int addTime) {
        date.setTime(date.getTime() + addTime * 1000);
        return date;
    }

    /**
     * 加多少分钟
     *
     * @param date
     *         时间
     * @param addTime
     *         分钟数据
     *
     * @return
     */
    public static Date addMinuteTime (Date date, int addTime) {
        date.setTime(date.getTime() + addTime * 1000 * 60);
        return date;
    }


    /**
     * 加多少小时
     *
     * @param date
     *         时间
     * @param addTime
     *         小时数据
     *
     * @return
     */
    public static Date addHourTime (Date date, int addTime) {
        date.setTime(date.getTime() + addTime * 1000 * 60 * 60);
        return date;
    }


    /**
     * 加多少天
     *
     * @param date
     *         时间
     * @param addTime
     *         天数据
     *
     * @return
     */
    public static Date addDayTime (Date date, int addTime) {
        date.setTime(date.getTime() + (1000L * 60 * 60 * 24 * addTime));
        return date;
    }

    /**
     * 加多少天
     *
     * @param date
     *         时间
     * @param addTime
     *         天数据
     *
     * @return
     */
    public static Date addDayTimeCalendar (Date date, int addTime) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, addTime);
        return calendar.getTime();
    }

    public static Date getLastWeekMonday() {
        Date date = new Date();
        Date a = DateUtils.addDays(date, -1);
        Calendar cal = Calendar.getInstance();
        cal.setTime(a);
        cal.add(Calendar.WEEK_OF_YEAR, -1);// 一周
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        Date time = cal.getTime();
        return time;
    }

    /**
     * 获取当月第一天
     * @return
     */
    public static Date getFirstDayOfMonth() {
        Calendar calendar=Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date theDate=calendar.getTime();
        GregorianCalendar gcLast=(GregorianCalendar)Calendar.getInstance();
        gcLast.setTime(theDate);
        //设置为第一天
        gcLast.set(Calendar.DAY_OF_MONTH, 1);
        return gcLast.getTime();
    }

    /**
     * 获取当月最后一天
     * @return
     */
    public static Date getForDatelast() {
        //获取Calendar
        Calendar calendar=Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        //设置日期为本月最大日期
        calendar.set(Calendar.DATE, calendar.getActualMaximum(calendar.DATE));
        return calendar.getTime();
    }

    /**
     * 检查日期是否在两个日期之内
     * @param startDate
     * @param endDate
     * @param checkDate
     * @return
     */
    public static Boolean checkDate(Date startDate, Date endDate, Date checkDate) {
        Interval interval = new Interval(new DateTime(startDate),
                new DateTime(endDate));
        return interval.contains(new DateTime(checkDate));
    }

    //判断选择的日期是否是今天
    public static boolean isToday(Date time) {
        return isThisTime(time, "yyyy-MM-dd");
    }

    //判断两个日期是否相等
    public static boolean isToday(Date time1,Date time2) {
        return isThisTime(time1, "yyyy-MM-dd",time2);
    }

    //判断选择的日期是否是本周
    public static boolean isThisWeek(Date time) {
        Calendar calendar = Calendar.getInstance();
        int currentWeek = calendar.get(Calendar.WEEK_OF_YEAR);
        calendar.setTime(time);
        int paramWeek = calendar.get(Calendar.WEEK_OF_YEAR);
        if (paramWeek == currentWeek) {
            return true;
        }
        return false;
    }

    //判断选择的日期是否是本月
    public static boolean isThisMonth(Date time) {
        return isThisTime(time, "yyyy-MM");
    }

    //判断选择的日期是否是上个月
    public static boolean isUpMonth(Date time) {
        return isUpTime(time, "yyyy-MM");
    }


    //判断选择的日期是否是本年
    public static boolean isThisYear(Date time) {
        return isThisTime(time, "yyyy");
    }

    //判断选择的日期是否是本季度
    public static boolean isThisQuarter(Date time) {
        Date QuarterStart = getCurrentQuarterStartTime();
        Date QuarterEnd = getCurrentQuarterEndTime();
        return time.after(QuarterStart) && time.before(QuarterEnd);
    }

    private static boolean isThisTime(Date time, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        String param = sdf.format(time);//参数时间
        String now = sdf.format(new Date());//当前时间
        if (param.equals(now)) {
            return true;
        }
        return false;
    }
    private static boolean isThisTime(Date time1, String pattern,Date time2) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        String param = sdf.format(time1);//参数时间
        String now = sdf.format(time2);//当前时间
        if (param.equals(now)) {
            return true;
        }
        return false;
    }
    private static boolean isUpTime(Date time, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        String param = sdf.format(time);//参数时间
        String now = sdf.format(addDayTime(new Date(),-1));//当前时间
        if (param.equals(now)) {
            return true;
        }
        return false;
    }

    /**
     * 获得季度开始时间
     * @return
     */
    public static Date getCurrentQuarterStartTime() {
        Calendar c = Calendar.getInstance();
        int currentMonth = c.get(Calendar.MONTH) + 1;
        SimpleDateFormat longSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");
        Date now = null;
        try {
            if (currentMonth >= 1 && currentMonth <= 3)
                c.set(Calendar.MONTH, 0);
            else if (currentMonth >= 4 && currentMonth <= 6)
                c.set(Calendar.MONTH, 3);
            else if (currentMonth >= 7 && currentMonth <= 9)
                c.set(Calendar.MONTH, 4);
            else if (currentMonth >= 10 && currentMonth <= 12)
                c.set(Calendar.MONTH, 9);
            c.set(Calendar.DATE, 1);
            now = longSdf.parse(shortSdf.format(c.getTime()) + " 00:00:00");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;
    }

    /**
     * 当前季度的结束时间
     * @return
     */
    public static Date getCurrentQuarterEndTime() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(getCurrentQuarterStartTime());
        cal.add(Calendar.MONTH, 3);
        return cal.getTime();
    }

    public static void main (String[] args) throws ParseException {

        /*String format1 = DateFormatUtils.format(getForDatelast(), DateUtils.YYYY_MM_DD_HH_MM_SS);
        System.out.println(format1);
        String format = DateFormatUtils.format(getFirstDayOfMonth(), DateUtils.YYYY_MM_DD_HH_MM_SS);
        System.out.println(format);
       // getLastWeekMonday();
        String startTime = DateFormatUtils.format(DateUtils.addMinuteTime(new Date(),-45),
                DateUtils.YYYY_MM_DD_HH_MM_SS) ;
        String endTime = DateFormatUtils.format(DateUtils.addMinuteTime(new Date(),-10),
                DateUtils.YYYY_MM_DD_HH_MM_SS) ;
        System.out.println(startTime);
        System.out.println(endTime);*/


        /*Boolean flga = checkDate(parseDate("2023-09-18"), parseDate("2023-09-22"), new Date());
        System.out.println(flga);*/


        try {
            System.out.println(getDayPoorminute(new Date(),new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2023-10" +
                    "-19 12:23:21")));
         /*   System.out.println("当天：" + DateUtils
                    .isToday(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2021-07-15 08:23:21")));
            System.out.println("本周：" + DateUtils
                    .isThisWeek(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2021-07-25 08:23:21")));
            System.out.println("本月：" + DateUtils
                    .isThisMonth(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2021-07-15 08:23:21")));
            System.out.println("本年：" + DateUtils
                    .isThisYear(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2022-07-15 08:23:21")));
            System.out.println("本季度：" + DateUtils
                    .isThisQuarter(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2021-07-15 08:23:21")));*/

        } catch (Exception pe) {
            System.out.println(pe.getMessage());
        }
    }


}
